#include "GY_SelectTreeDialog.h"
#include "ui_GY_SelectTreeDialog.h"
#include <QTreeWidgetItem>
GY_SelectTreeDialog::GY_SelectTreeDialog(QVector<QVector<QVariant>> nodes, QString oldPid, QWidget *parent) :
    nodes(nodes),
    QDialog(parent),
    ui(new Ui::GY_SelectTreeDialog)
{
    ui->setupUi(this);
    ui->pushButton_accept->setEnabled(false);



    for (QVector<QVariant> row : nodes) {
        QString groupId = row[0].toString();
        QString groupName = row[1].toString();
        QString pid = row[2].toString();
        if("0" == pid){  //是顶级分类
            QTreeWidgetItem* group = new QTreeWidgetItem(ui->treeWidget,QStringList({groupName,groupId}));
            ui->treeWidget->addTopLevelItem(group);
            if(oldPid == groupId){
                ui->treeWidget->setCurrentItem(group);
            }
        }
        else{  //不是顶级分类
            //查找上级分类
            QTreeWidgetItemIterator itor(ui->treeWidget);
            while (*itor) {
                if(pid == (*itor)->text(GroupId)){  //id相同
                    QTreeWidgetItem* group = new QTreeWidgetItem(*itor,QStringList({groupName,groupId}));
                    (*itor)->addChild(group);
                    if(oldPid == groupId){
                        ui->treeWidget->setCurrentItem(group);
                    }
                    break;
                }
                ++itor;
            }

        }
    }



}

GY_SelectTreeDialog::~GY_SelectTreeDialog()
{
    delete ui;
}

QString GY_SelectTreeDialog::getGroupName() const
{
    return groupName;
}

int GY_SelectTreeDialog::getGroupId() const
{
    return groupId;
}

void GY_SelectTreeDialog::on_treeWidget_clicked(const QModelIndex &index)
{
    if(!index.isValid()){
        return;
    }
    groupName = ui->treeWidget->currentItem()->text(NodeName);
    groupId = ui->treeWidget->currentItem()->text(GroupId).toInt();

    ui->pushButton_accept->setEnabled(true);
}

void GY_SelectTreeDialog::on_pushButton_reject_clicked()
{
    reject();
}

void GY_SelectTreeDialog::on_pushButton_accept_clicked()
{
    accept();
}

void GY_SelectTreeDialog::on_pushButton_root_clicked()
{
    groupId = 0;
    accept();
}
